package example.documentbased.editorModule.controller
{
	import example.documentbased.editorModule.views.popUps.SaveAsPopUp;
	import example.documentbased.mainModule.controller.ICommonController;
	import example.documentbased.mainModule.models.factories.ItemsFactory;
	import example.documentbased.mainModule.models.vo.DocumentVO;
	import example.documentbased.mainModule.services.delegates.IMainServiceDelegate;
	
	import flash.events.Event;
	
	import org.etherframework.controller.IReactiveCommand;
	import org.etherframework.controller.ReactiveCommand;
	import org.etherframework.controller.common.PopUpModel;
	
	import raix.reactive.IObservable;
	import raix.reactive.Observable;
	import raix.reactive.Unit;
	
	public class SaveAsDocumentCommand extends ReactiveCommand
	{
		private var _document:DocumentVO;
		private var _serviceDelegate:IMainServiceDelegate;
		private var _editorController:IEditorController;
		private var _commonController:ICommonController;
		private var _itemFactory:ItemsFactory;
		
		public function SaveAsDocumentCommand(editorController:IEditorController, 
											  commonController:ICommonController,
											  serviceDelegate:IMainServiceDelegate, 
											  itemFactory:ItemsFactory)
		{
			_editorController = editorController;
			_commonController = commonController;
			_serviceDelegate = serviceDelegate;
			_itemFactory = itemFactory;
		}
		
		public function initialize(document:DocumentVO):IReactiveCommand
		{
			_document = document;
			markAsInitialized();
			
			return this;
		}
		
		override public function observable():IObservable
		{
			var popUpModel:PopUpModel = new PopUpModel("Save Document As", _document.name);
			
			return _commonController.getShowPopUpCommand(SaveAsPopUp, popUpModel).observable()
				.mapMany(function(event:Event):IObservable
				{
					if (event.type == Event.COMPLETE)
					{
						var newName:String = SaveAsPopUp(popUpModel.popUp).editedName;
						var newDoc:DocumentVO = _itemFactory.createDocumentVO(
							"", _document.uid, _document.editorId, newName, _document.text);
						
						return _editorController.getSaveDocumentCommand(newDoc).observable();
					}
					return Observable.value(new Unit());
					
				});
		}
	}
}